
#include <cstdio>
#include "IGLState.h"

using namespace BWE;

IGLState::IGLState()
{
	frameBuffer = 0;
}
IGLState::~IGLState()
{

}

void IGLState::print(const BString& head)
{
	BString message;
	message << head << " frame buffer : " << frameBuffer << " : ";
	message << head << " viewport : ";
	message << viewport[0] << ","; 
	message << viewport[1] << ",";
	message << viewport[2] << ",";
	message << viewport[3];
	puts(message.cstr());
}

void IGLState::save()
{
	//frame buffer
	glGetIntegerv(GL_FRAMEBUFFER_BINDING, &frameBuffer);

	//attribs
	glPushAttrib(GL_ALL_ATTRIB_BITS);

	//viewport
	glGetIntegerv(GL_VIEWPORT, viewport);

	//matrices
#ifdef REAL_IS_DOUBLE
	glMatrixMode(GL_PROJECTION);
	glGetDoublev(GL_PROJECTION_MATRIX, (GLdouble*)&projectionMatrix);
	glMatrixMode(GL_MODELVIEW);
	glGetDoublev(GL_MODELVIEW_MATRIX, (GLdouble*)&modelViewMatrix);
	glMatrixMode(GL_TEXTURE);
	glGetDoublev(GL_TEXTURE_MATRIX, (GLdouble*)&textureMatrix);
#else
	glMatrixMode(GL_PROJECTION);
	glGetFloatv(GL_PROJECTION_MATRIX, (GLfloat*)&projectionMatrix);
	glMatrixMode(GL_MODELVIEW);
	glGetFloatv(GL_MODELVIEW_MATRIX, (GLfloat*)&modelViewMatrix);
	glMatrixMode(GL_TEXTURE);
	glGetFloatv(GL_TEXTURE_MATRIX, (GLfloat*)&textureMatrix);
#endif
}
void IGLState::open()
{
	//matrices
#ifdef REAL_IS_DOUBLE
	glMatrixMode(GL_TEXTURE);
	glLoadMatrixd((GLdouble*)&textureMatrix);
	glMatrixMode(GL_MODELVIEW);
	glLoadMatrixd((GLdouble*)&modelViewMatrix);
	glMatrixMode(GL_PROJECTION);
	glLoadMatrixd((GLdouble*)&projectionMatrix);
#else
	glMatrixMode(GL_TEXTURE);
	glLoadMatrixf((GLfloat*)&textureMatrix);
	glMatrixMode(GL_MODELVIEW);
	glLoadMatrixf((GLfloat*)&modelViewMatrix);
	glMatrixMode(GL_PROJECTION);
	glLoadMatrixf((GLfloat*)&projectionMatrix);
#endif

	//viewport
	glViewport(viewport[0], viewport[1], viewport[2], viewport[3]);

	//attribs
	glPopAttrib();

	//frame buffer
	glBindFramebuffer(GL_FRAMEBUFFER, frameBuffer);
}
